package middleware

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"naio/pkg/logger"
	"time"
)

func AccessLog() gin.HandlerFunc {
	return func(c *gin.Context) {
		params := &logger.LogParams{}
		// 开始时间
		startTime := time.Now()
		params.StartTime = startTime.Format("2006-01-02 15:04:05.000")

		// 处理请求
		c.Next()

		// 结束时间
		endTime := time.Now()
		params.EndTime = endTime.Format("2006-01-02 15:04:05.000")

		// 执行时间
		params.Duration = endTime.Sub(startTime)
		// 请求ip
		params.Ip = c.ClientIP()
		// 请求方法
		params.Method = c.Request.Method
		// 请求uri
		params.RequestUrI = c.Request.RequestURI
		//params.RequestUrI = c.Request.URL.Path
		// 状态码
		params.StatusCode = c.Writer.Status()

		paramsStr, _ := json.Marshal(params)
		logger.Default().Info("log:", string(paramsStr))
	}
}
